package com.yuanfeng.business.service.impl;

import com.alibaba.csp.sentinel.util.StringUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.yuanfeng.business.entity.ShopBaseEntity;
import com.yuanfeng.business.entity.ShopRetentionMoneyRecordEntity;
import com.yuanfeng.business.mapper.ShopBaseMapper;
import com.yuanfeng.business.mapper.ShopRetentionMoneyRecordMapper;
import com.yuanfeng.business.service.ShopRetentionMoneyRecordService;
import com.yuanfeng.business.vo.ShopDetailEntityExpVO;
import com.yuanfeng.business.vo.ShopDetailVO;
import com.yuanfeng.commoms.config.YFConfig;
import com.yuanfeng.commoms.exception.BizCodeEnume;
import com.yuanfeng.commoms.util.*;
import com.yuanfeng.commoms.util.excel.ExcelsUtil;
import com.yuanfeng.commoms.util.querypage.PageUtils;
import com.yuanfeng.commoms.util.querypage.Query;
import com.yuanfeng.commoms.vo.base.BaseSysConfigsVO;
import com.yuanfeng.commoms.vo.base.PlatformoperationVO;
import com.yuanfeng.commoms.vo.goods.GoodsDetailsListVO;
import com.yuanfeng.commoms.vo.order.OrderComplaintsVO;
import com.yuanfeng.commoms.vo.payment.PayRecordVO;
import com.yuanfeng.commoms.vo.shop.RetentionShopInfoVO;
import com.yuanfeng.commoms.vo.user.UserInfoVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @ClassName ShopRetentionMoneyRecordServiceImpl
 * @Description  质保金充值，提现记录
 * @Author cyp
 * @Date 2023-08-21 13:42:42
 * @Version 1.0
 **/
@Service
public class ShopRetentionMoneyRecordServiceImpl extends ServiceImpl<ShopRetentionMoneyRecordMapper, ShopRetentionMoneyRecordEntity>
        implements ShopRetentionMoneyRecordService {

    @Autowired
    private ShopBaseMapper shopBaseMapper;
    @Override
    public ResponseResult recharge(Map<String, Object> map) {
        String token = String.valueOf(map.get("token"));
        UserInfoVO userInfo = ParseTokenUtils.getPlatformUser(token);
        if (userInfo == null ){
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID.getCode(),BizCodeEnume.TOKEN_IS_INVALID.getMsg());
        }
        Integer integer = 0;
        map.put("shopId",userInfo.getShopId());

        if (map.get("rechargeType").equals(1)) {

            //支付成功
            map.put("rechargeStatus", 1);
            List payImg = (List) map.get("payImg");
            String s = JSON.toJSONString(payImg);
            map.put("payImg",s);


            //充值金额
            BigDecimal pay = new BigDecimal(String.valueOf(map.get("payPrice")));

            //将审核通过未赔付的投诉单进行赔付
            unpaidorders(pay,userInfo.getShopId());

            //查询质保金信息
            RetentionShopInfoVO selectretention = this.baseMapper.selectRetention(userInfo.getShopId());
            BigDecimal payPrice = selectretention.getRetentionMoneyBalance().add(pay);//质保金余额-

            //质保金可提现
            BigDecimal payPrice1 = payPrice.subtract(selectretention.getRetentionMoneyLimit());
            if (payPrice1.compareTo(new BigDecimal(0)) == -1){
                payPrice1 = new BigDecimal(0);
            }

            //待补缴
            BigDecimal payPrice2 = selectretention.getRetentionMoneyPayment().subtract(pay);//待补缴金额
            if (payPrice2.compareTo(new BigDecimal(0)) == -1){
                payPrice2 = new BigDecimal(0);
            }

            map.put("payPrice",payPrice);
            map.put("payPrice1",payPrice1);
            map.put("payPrice2",payPrice2);
            if (payPrice.compareTo(selectretention.getRetentionMoneyLimit()) >= 0) {
                map.put("retentionStatus", 1);
            } else if (payPrice.compareTo(new BigDecimal(0)) >= 0 && payPrice2.compareTo(new BigDecimal(0)) > 0) {
                //发送站内信
                String content = "亲爱的卖家您好，根据平台质保金规则您需补缴" + payPrice2 + " 元质保金，请登录商家后台查询。";
                this.baseMapper.insertSysMessage("",userInfo.getUserId(),"",5,
                        "补缴质保金",content, String.valueOf(userInfo.getShopId()));

                map.put("retentionStatus", 2);
            } else if (payPrice.compareTo(new BigDecimal(0)) == -1) {
                //发送站内信
                String content = "亲爱的卖家您好，根据平台质保金规则您需补缴" + payPrice2 + " 元质保金，请登录商家后台查询。";
                this.baseMapper.insertSysMessage("",userInfo.getUserId(),"",5,
                        "补缴质保金",content, String.valueOf(userInfo.getShopId()));

                map.put("retentionStatus", 3);
                map.put("paymentTime", new Date());
            }
            //更新shopbase表
            if(selectretention.getRetentionStatus() == 3){
                map.put("paymentTime", null);
            }
            this.baseMapper.updateshopbase(map);

            map.put("payPrice",pay);
            map.put("fundDestination",3);
            integer = this.baseMapper.insertRetentionMoney(map);
            if (integer > 0){
                return ResponseResult.success(1,"充值成功",1);
            }
        } else if (map.get("rechargeType").equals(2)) {
            //对公转账
            map.put("rechargeStatus", 0);
            List payImg = (List) map.get("payImg");
            map.put("payImg", JSON.toJSONString(payImg));
            map.put("fundDestination",3);
            integer = this.baseMapper.insertRetentionMoney(map);
            if (integer > 0){
                return ResponseResult.success(1,"充值成功",2);
            }
        }
        return ResponseResult.fail();
    }

    @Override
    public ResponseResult queryRecord(Map<String, Object> map) {
        HashMap<Object, Object> hashMap = new HashMap<>();
        String token = String.valueOf(map.get("token"));
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(token);
        if (userInfo == null ){
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID.getCode(),BizCodeEnume.TOKEN_IS_INVALID.getMsg());
        }

        Integer shopId = Integer.valueOf(userInfo.getShopId());
        map.put("shopId",shopId);

        IPage<ShopRetentionMoneyRecordEntity> page=this.baseMapper.queryRecord(new Query<ShopRetentionMoneyRecordEntity>().getPage(map),
                map);
        return ResponseResult.success(PageUtils.getPage(page));
    }

    @Override
    public ResponseResult selectsEndTime() {
        //查询质保金说明
        BaseSysConfigsVO pos = shopBaseMapper.selectByConfigType("platform_operation_specifications");
        if (pos == null){
            return ResponseResult.fail(BizCodeEnume.NO_INFORMATION_OBTAINED);
        }
        PlatformoperationVO platform = JSONObject.parseObject(pos.getConfigValue(), PlatformoperationVO.class);
        return ResponseResult.success(platform.getDeliveryTime());
    }

    @Override
    public ResponseResult withdRawal(Map<String, Object> map) {

        Map<String,Object> assetDetailMap = new HashMap<>();
        Map<String,Object> ManageMoney = new HashMap<>();
        String token = String.valueOf(map.get("token"));
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(token);
        if (userInfo == null ){
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID.getCode(),BizCodeEnume.TOKEN_IS_INVALID.getMsg());
        }
        String userId = userInfo.getUserId();
        String amount = String.valueOf(map.get("amount"));

        //生成单号
        StringBuffer id = new StringBuffer("W");
        DateFormat dFormat3 = new SimpleDateFormat("yyyyMMdd");

        String format = dFormat3.format(new Date());

        Random random = new Random();
        String verificationCode = String.valueOf(random.nextInt(9) + 1);
        for (int i = 0; i < 5; i++) {
            verificationCode += random.nextInt(10);
        }
        id.append(format).append(verificationCode);

        //更新质保金余额
        updateshopmoney1(Integer.valueOf(userInfo.getShopId()),new BigDecimal(amount));

        //查询账户余额
        String balance = this.baseMapper.queryAccountBalance(userInfo.getUserId());

        Double Money = Double.parseDouble(balance) + Double.parseDouble(amount);
        //余额充值
        assetDetailMap.put("detailType", 11);
        assetDetailMap.put("assetType", 1);
        assetDetailMap.put("assetAmount", Double.parseDouble(amount));
        assetDetailMap.put("assetDirection", "质保金提现");
        assetDetailMap.put("payType", 1);
        assetDetailMap.put("userId", userId);
        assetDetailMap.put("orderId", id.toString());
        ManageMoney.put("money", Money);
        ManageMoney.put("userId", userId);
        this.baseMapper.updateCardMemberDetailPort(ManageMoney);

        //提现成功
        map.put("fundDestination", 1);
        map.put("rType", 2);
        map.put("payPrice", amount);
        map.put("shopId", userInfo.getShopId());
        map.put("orderId", id.toString());
        map.put("rechargeType", 0);
        map.put("rechargeStatus", 1);
        Integer integer = this.baseMapper.insertRetentionMoney(map);

        this.baseMapper.insertDetail(assetDetailMap);

        Map<String, Object> comRecord = new HashMap<String, Object>();
        SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd");
        String recordDate = dateformat.format(new Date());
        String[] reDate = recordDate.split("-");
        String year = reDate[0];
        String month = reDate[1];
        String day = reDate[2];
        String recordTitle = "质保金提现";
        String record_desc = "质保金提现";
        int tradeTypeId = 3;
        int userType = 1;
        int recordWithdraw = 0;
        double osCommisAmount = 0;
        double osCommisReturnAmount = 0;
        comRecord.put("recordDate", recordDate);
        comRecord.put("recordMoney", amount);
        comRecord.put("orderId", id.toString());
        comRecord.put("year", year);
        comRecord.put("month", month);
        comRecord.put("day", day);
        comRecord.put("plusOrMinus", 1);
        comRecord.put("recordTitle", recordTitle);
        comRecord.put("record_desc", record_desc);
        comRecord.put("tradeTypeId", tradeTypeId);
        comRecord.put("userType", userType);
        comRecord.put("recordWithdraw", recordWithdraw);
        comRecord.put("osCommisAmount", osCommisAmount);
        comRecord.put("osCommisReturnAmount", osCommisReturnAmount);
        comRecord.put("money", Money);
        comRecord.put("userId", userId);
        comRecord.put("isCurrentUser",1);//判断当前订单是否属于当前用户 1 是 2 否
        this.baseMapper.insertConsumeRecordport(comRecord);

        if (integer > 0){
            return ResponseResult.success("提现成功");
        }
        return ResponseResult.fail(0, "提现失败");
    }

    @Override
    public ResponseResult qureyBill(Map<String, Object> map) {
        String token = String.valueOf(map.get("token"));
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(token);
        if (userInfo == null ){
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID.getCode(),BizCodeEnume.TOKEN_IS_INVALID.getMsg());
        }
        HashMap<Object, Object> hashMap = new HashMap<>();
        Integer shopId = Integer.valueOf(userInfo.getShopId());
        map.put("shopId",shopId);

        if (StringUtils.isEmpty(map.get("startTime"))){
            map.put("startTime",null);
        }
        if (StringUtils.isEmpty(map.get("endTime"))){
            map.put("endTime",null);
        }

        if (!StringUtils.isEmpty(map.get("time"))){
            Integer time = (Integer) map.get("time");
            if (time == 1){
                //昨天
                Map yesterdayTime = DateUtils.getYesterdayTime();
                map.put("startTime",yesterdayTime.get("startDate"));
                map.put("endTime",yesterdayTime.get("endDate"));
            }else if (time == 2){
                //本月
                Map monthTime = DateUtils.getMonthTime();
                map.put("startTime",monthTime.get("startDate"));
                map.put("endTime",monthTime.get("endDate"));
            }else if (time == 3){
                //上个月
                try {
                    Map lastmonthTime = DateUtils.getLastMonthTime();
                    map.put("startTime",lastmonthTime.get("startDate"));
                    map.put("endTime",lastmonthTime.get("endDate"));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        IPage<ShopDetailVO> page=this.baseMapper.queryComplaintsRecord(new Query<ShopDetailVO>().getPage(map),
                map);


        return ResponseResult.success(PageUtils.getPage(page));
    }

    @Override
    public ResponseResult qureyComplaint(Map<String, Object> map) {
        String token = String.valueOf(map.get("token"));
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(token);
        if (userInfo == null ){
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID.getCode(),BizCodeEnume.TOKEN_IS_INVALID.getMsg());
        }
        HashMap<Object, Object> hashMap = new HashMap<>();
        Integer shopId = Integer.valueOf(userInfo.getShopId());
        map.put("shopId",shopId);
        if (StringUtils.isEmpty(map.get("startTime"))){
            map.put("startTime",null);
        }
        if (StringUtils.isEmpty(map.get("endTime"))){
            map.put("endTime",null);
        }
        IPage<OrderComplaintsVO> page=this.baseMapper.qureyComplaint(new Query<OrderComplaintsVO>().getPage(map),
                map);
        List<OrderComplaintsVO> lists =  page.getRecords();
        for (OrderComplaintsVO entity : lists) {
            String goodsId = entity.getComplaintsGoodsid();
            List<Integer> list1 = JSON.parseArray(goodsId, Integer.class);
            entity.setComplaintsGoodsids(list1);
            if (list1 != null && list1.size() > 0){
                HashMap<String, Object> map1 = new HashMap<>();
                String orderId = entity.getOrderId();
                // 退单关联商品
                if (!orderId.startsWith("T")){
                    map1.put("orderId",orderId);
                    map1.put("list",list1);
                    List<GoodsDetailsListVO> orderGoods = this.baseMapper.queryGoodsList(map1);
                    entity.setGoods(orderGoods);
                }
            }
        }
        //获取本月罚款额度
        Map monthTime = DateUtils.getMonthTime();
        Map<String, Object> map1 = new HashMap<>();
        map1.put("start",monthTime.get("startDate"));
        map1.put("end",monthTime.get("endDate"));
        map1.put("shopId",userInfo.getShopId());
        //查询质保金信息
        ShopBaseEntity selectretention = shopBaseMapper.selectById(userInfo.getShopId());
        //查待处理投诉单
        Integer integer1 = 0;
        integer1 = this.baseMapper.selectretentiontotal(userInfo.getShopId(), 0);
        //累计投诉单
        Integer integer2 = 0;
        integer2 = this.baseMapper.selectretentiontotal(userInfo.getShopId(), 1);

        String s = this.baseMapper.querymonthFine(map1);
        if (s == null || s == ""){
            s = "0";
        }
        String totalFine=this.baseMapper.queryAllFine(userInfo.getShopId());
        hashMap.put("totalFine",totalFine);//累计赔付金额
        hashMap.put("pendingProcessing",integer1);//待处理投诉单
        hashMap.put("accumulateComplaints",integer2);//累计投诉单
        hashMap.put("monthFine",s);//当月赔付
        hashMap.put("list",lists);//当月赔付
        hashMap.put("totalCount",page.getTotal());//
        return ResponseResult.success(hashMap);
    }

    @Override
    public ResponseResult handlingComplaints(Map<String, Object> map) {

        String token = String.valueOf(map.get("token"));
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(token);
        if (userInfo == null ){
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID.getCode(),BizCodeEnume.TOKEN_IS_INVALID.getMsg());
        }
        HashMap<Object, Object> hashMap = new HashMap<>();
        Integer shopId = Integer.valueOf(userInfo.getShopId());
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        map.put("shopId",shopId);
        Integer status = (Integer) map.get("status");
        String complaintsId = String.valueOf(map.get("complaintsId"));//投诉单号
        if (status == 1) {
            map.put("complaintsStatus",1);
            //商家同意赔付
            //查询投诉单信息
            OrderComplaintsVO querycomplaintsid = this.baseMapper.queryComplaintsId(complaintsId);
            if (querycomplaintsid == null){
                return ResponseResult.fail(0, "投诉单号信息有误");
            }
            map.put("fundDestination",1);//资金去向  用户余额
            //更新商家质保金
            Integer integer = updateshopmoney(shopId, querycomplaintsid.getCompensationAmount());
            if (integer == 1){
                //质保金足额 已赔付
                map.put("compensationStatus",1);

                //将金额存入用户余额
                insert(querycomplaintsid.getUserId(),
                        querycomplaintsid.getCompensationAmount().toString(), querycomplaintsid.getOrderId());
            }else if (integer == 0){
                //质保金不足 未赔付
                map.put("compensationStatus",0);
            }else{
                return ResponseResult.fail(0, "更新质保金异常");
            }

            List sellerVoucher = (List) map.get("sellerVoucher");
            String string = JSON.toJSONString(sellerVoucher);
            map.put("sellerVoucher",string);

            Integer integer1 = this.baseMapper.handlingComplaints(map);

            if (integer1 > 0){
               return ResponseResult.success("赔付成功");
            }else{
                return ResponseResult.fail(0, "赔付失败");
            }
        } else if (status == 2) {
            //商家申请上诉
            map.put("complaintsStatus", 4);
            map.put("isAppeal", 1);
            List sellerVoucher = (List) map.get("sellerVoucher");
            String string = JSON.toJSONString(sellerVoucher);
            map.put("sellerVoucher",string);
            Calendar instance = Calendar.getInstance();
            instance.add(Calendar.DATE,3);

            map.put("failureTime",format.format(instance.getTime()));

            Integer integer = this.baseMapper.handlingComplaints(map);
            if (integer > 0){
                return ResponseResult.success("申诉成功");
            }else{
                return ResponseResult.fail(0, "申诉失败");
            }

        }
        return ResponseResult.success();
    }

    @Override
    public ResponseResult qureyComplaintDetail(Map<String, Object> map) {
        String token = String.valueOf(map.get("token"));
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(token);
        if (userInfo == null ){
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID.getCode(),BizCodeEnume.TOKEN_IS_INVALID.getMsg());
        }
        Integer complaintsId = (Integer) map.get("id");
        //查询投诉单信息
        OrderComplaintsVO querycomplaintsid = this.baseMapper.queryComplaintsId1(complaintsId);
        if (querycomplaintsid != null) {
            String complaintsVoucher = querycomplaintsid.getComplaintsVoucher();
            List<String> strings = JSON.parseArray(complaintsVoucher, String.class);
            querycomplaintsid.setComplaintsVouchers(strings);

            String sellerVoucher = querycomplaintsid.getSellerVoucher();
            List<String> strings1 = JSON.parseArray(sellerVoucher, String.class);
            querycomplaintsid.setSellerVouchers(strings1);

            String goodsid = querycomplaintsid.getComplaintsGoodsid();
            List<Integer> list1 = JSON.parseArray(goodsid, Integer.class);
            querycomplaintsid.setComplaintsGoodsids(list1);

            String orderId = querycomplaintsid.getOrderId();
            if (orderId.startsWith("T")){
                OrderComplaintsVO querycomplaintsid1 = this.baseMapper.queryComplaintsId(orderId);
                querycomplaintsid.setCorrelationComplaint(querycomplaintsid1);
            }
        }
        String goodsid = querycomplaintsid.getComplaintsGoodsid();
        List<Integer> list1 = JSON.parseArray(goodsid, Integer.class);
        querycomplaintsid.setComplaintsGoodsids(list1);
        if (list1 != null && list1.size() > 0){
            HashMap<String, Object> map1 = new HashMap<>();
            map1.put("orderId",querycomplaintsid.getOrderId());
            map1.put("list",list1);
            List<GoodsDetailsListVO> orderGoods = this.baseMapper.queryGoodsList(map1);
            querycomplaintsid.setGoods(orderGoods);
        }
        return ResponseResult.success(querycomplaintsid);
    }

    @Override
    public ResponseResult qureyBillExp(Map<String, Object> map) {
        String token = String.valueOf(map.get("token"));
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(token);
        if (userInfo == null ){
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID.getCode(),BizCodeEnume.TOKEN_IS_INVALID.getMsg());
        }
        Integer shopId = Integer.valueOf(userInfo.getShopId());
        map.put("shopId",shopId);

        if (StringUtils.isEmpty(map.get("startTime"))){
            map.put("startTime",null);
        }
        if (StringUtils.isEmpty(map.get("endTime"))){
            map.put("endTime",null);
        }

        if (!StringUtils.isEmpty(map.get("time"))){
            Integer time = (Integer) map.get("time");
            if (time == 1){
                //昨天
                Map yesterdayTime = DateUtils.getYesterdayTime();
                map.put("startTime",yesterdayTime.get("startDate"));
                map.put("endTime",yesterdayTime.get("endDate"));
            }else if (time == 2){
                //本月
                Map monthTime = DateUtils.getMonthTime();
                map.put("startTime",monthTime.get("startDate"));
                map.put("endTime",monthTime.get("endDate"));
            }else if (time == 3){
                //上个月
                try {
                    Map lastmonthTime = DateUtils.getLastMonthTime();
                    map.put("startTime",lastmonthTime.get("startDate"));
                    map.put("endTime",lastmonthTime.get("endDate"));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        IPage<ShopDetailEntityExpVO> page=this.baseMapper.queryComplaintsRecordExp(new Query<ShopDetailEntityExpVO>().getPage(map),
                map);
        if (CollectionUtils.isEmpty(page.getRecords())){
            return ResponseResult.fail(0, "暂无账单明细");
        }
        for (ShopDetailEntityExpVO entity : page.getRecords()) {
            if (entity.getFundDestination() != null && entity.getFundDestination() == 1){
                entity.setFundDestinations("消费者账户");
            }else if (entity.getFundDestination() != null && entity.getFundDestination() == 2){
                entity.setFundDestinations("平台账户");
            }else if (entity.getFundDestination() != null && entity.getFundDestination() == 3){
                entity.setFundDestinations("质保金余额");
            }else{
                entity.setFundDestinations("");
            }

            if (entity.getRechargeType() != null && entity.getRechargeType() == 0){
                entity.setRechargeTypes("质保金余额");
            }else if (entity.getRechargeType() != null && entity.getRechargeType() == 1) {
                entity.setRechargeTypes("余额支付");
            }else if (entity.getRechargeType() != null && entity.getRechargeType() == 2) {
                entity.setRechargeTypes("对公转账");
            }else if (entity.getRechargeType() != null && entity.getRechargeType() == 3) {
                entity.setRechargeTypes("平台充值");
            }else{
                entity.setRechargeTypes("");
            }

            if (entity.getReason() != null && entity.getReason() == -1){
                entity.setReasons("充值");
            }else if (entity.getReason() != null && entity.getReason() == -2){
                entity.setReasons("提现");
            }else if (entity.getReason() != null && entity.getReason() == -3){
                entity.setReasons("补缴");
            }else if (entity.getReason() != null && entity.getReason() == 1){
                entity.setReasons("未按时发货");
            }else if (entity.getReason() != null && entity.getReason() == 2){
                entity.setReasons("虚假发货");
            }else if (entity.getReason() != null && entity.getReason() == 3){
                entity.setReasons("违规出售商品");
            }else if (entity.getReason() != null && entity.getReason() == 4){
                entity.setReasons("骚扰辱骂");
            }else if (entity.getReason() != null && entity.getReason() == 5){
                entity.setReasons("售后退款");
            }else {
                entity.setReasons("");
            }
        }
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        String[] title = {"时间", "原因", "金额", "来源账户", "去向账户", "业务描述/备注", "业务订单号", "投诉单号"};
        List<Map<String, String>> list = Lists.newArrayList();

        for(ShopDetailEntityExpVO data:page.getRecords()){
            Map<String, String> map1 = new HashMap<>();
            map1.put("时间", format.format(data.getCreateTime()));
            map1.put("原因", data.getReasons());
            map1.put("金额", data.getAmount()+"");
            map1.put("来源账户", data.getRechargeTypes());
            map1.put("去向账户", data.getFundDestinations());
            map1.put("业务描述/备注", data.getComplaintsReason() == null ? null : data.getComplaintsReason());
            map1.put("业务订单号", data.getOrderId() == null ? null : data.getOrderId());
            map1.put("投诉单号", data.getComplaintsId() == null ? null : data.getComplaintsId());


            list.add(map1);

        }

        Map<String/* 此处的key为每个sheet的名称，一个excel中可能有多个sheet页 */, List<Map<String/* 此处key对应每一列的标题 */, String>>/*
         * 该list为每个sheet页的数据
         */> map2 = Maps
                .newHashMap();
        map2.put("测试合并数据", list);
        String url = ExcelsUtil.createExcel(title, map2,
                new int[]{0}/* 此处数组为需要合并的列，可能有的需求是只需要某些列里面相同内容合并 */);
        return ResponseResult.success(url);
    }

    @Override
    public ResponseResult queryShopDetail(Map<String, Object> map) {
        HashMap<Object, Object> hashMap = new HashMap<>();
        boolean isExistToken = RedisUtil.exists(YFConfig.YF_PLATFORM_TOKEN_USER+ String.valueOf(map.get("token")));

        if (!isExistToken) {
            return ResponseResult.fail(BizCodeEnume.INSUFFICIENT_PERMISSIONS);
        }


        IPage<ShopDetailVO> page=this.baseMapper.queryComplaintsRecord2(new Query<ShopDetailVO>().getPage(map),
                map);

        return ResponseResult.success(PageUtils.getPage(page));
    }

    @Override
    public ResponseResult insertShopComplaints(Map<String, Object> map) {
        boolean isExistToken = RedisUtil.exists(YFConfig.YF_PLATFORM_TOKEN_USER + String.valueOf(map.get("token")));

        if (!isExistToken) {
            return ResponseResult.fail(BizCodeEnume.INSUFFICIENT_PERMISSIONS);
        }
        Integer shopId = (Integer) map.get("shopId");
        BigDecimal amount = new BigDecimal(String.valueOf(map.get("compensationAmount")));//获取罚款金额
        //生成投诉单号
        StringBuffer id = new StringBuffer("TS");
        DateFormat dFormat3 = new SimpleDateFormat("yyyyMMdd");

        String format = dFormat3.format(new Date());

        Random random = new Random();
        String userId = null;
        String verificationCode = String.valueOf(random.nextInt(9) + 1);
        for (int i = 0; i < 5; i++) {
            verificationCode += random.nextInt(10);
        }
        id.append(format).append(verificationCode);
        map.put("complaintsId",id.toString());

        //判断是订单号还是投诉单号
        String oddNumbers = String.valueOf(map.get("oddNumbers"));
        if (oddNumbers != null && oddNumbers != "" && PayToolUtil.isInteger(oddNumbers)) {
            map.put("orderId",oddNumbers);
            userId = this.baseMapper.selectOrderUserId(oddNumbers);
            //查询订单商品信息
            List<Integer> selectgoodsid = this.baseMapper.selectGoodsId(oddNumbers);
            String string = JSON.toJSONString(selectgoodsid);
            map.put("complaintsGoodsid",string);
        }else{
            map.put("orderId",oddNumbers);
            //查询该投诉单是否关联订单
            Map<String, Object> map1 = this.baseMapper.selectOrderId(oddNumbers);
            userId = map1.get("user_id").toString();
            String s = String.valueOf(map1.get("order_id"));
            if (s != null && s != ""){
                //map.put("orderId",s);
                //查询订单商品信息
                List<Integer> selectgoodsid =  this.baseMapper.selectGoodsId(s);
                String string = JSON.toJSONString(selectgoodsid);
                map.put("complaintsGoodsid",string);
            }

        }
        //根据手机号查询用户id
        map.put("userId",userId);
        //查询质保金信息
        Integer addcomplaints = 0;

        RetentionShopInfoVO selectretention =  this.baseMapper.selectRetention(map.get("shopId").toString());
        BigDecimal balance = selectretention.getRetentionMoneyBalance();//质保金余额

        if (amount.compareTo(balance) > 0) {
            //质保金余额不足 暂不赔付
            map.put("compensationStatus", 0);
        } else {
            map.put("compensationStatus", 1);
            if (map.get("fundDestination").equals(1)){
                //将罚款转与消费者余额
                determinedeliverytime2(userId, amount, oddNumbers);
            }
        }
        //修改质保金余额
        updateshopmoney(shopId, amount);
        map.put("complaintsStatus",1);
        map.put("isPlatform",1);

        addcomplaints = this.baseMapper.addComplaints(map);

        if (addcomplaints > 0){
            return ResponseResult.success(BizCodeEnume.GUARANTEE_SUCCESS);
        }

        return ResponseResult.fail(BizCodeEnume.GUARANTEE_FAILED);
    }

    @Override
    public ResponseResult platformRecharge(Map<String, Object> map) {
        boolean isExistToken = RedisUtil.exists(YFConfig.YF_PLATFORM_TOKEN_USER  + String.valueOf(map.get("token")));

        if (!isExistToken) {
            return ResponseResult.fail(BizCodeEnume.INSUFFICIENT_PERMISSIONS);
        }
        HashMap<String, Object> record = new HashMap<>();
        String shopId = map.get("shopId").toString();
        BigDecimal amount = new BigDecimal(String.valueOf(map.get("amount")));//获取充值金额
        //将未赔付的投诉单进行赔付
        unpaidorders(amount,shopId);

        //生成单号
        StringBuffer id = new StringBuffer();
        DateFormat dFormat3 = new SimpleDateFormat("yyyyMMdd");

        String format = dFormat3.format(new Date());

        Random random = new Random();
        String verificationCode = String.valueOf(random.nextInt(9) + 1);
        for (int i = 0; i < 5; i++) {
            verificationCode += random.nextInt(10);
        }
        id.append(format).append(verificationCode);

        //更改店铺质保金余额
        Integer integer = addshopmoney(shopId, amount);
        //插入充值记录表
        record.put("shopId", shopId);
        record.put("payPrice", amount);
        record.put("rechargeType", 3);
        record.put("rechargeStatus", 1);
        record.put("rType", 1);
        record.put("payExplanation", map.get("explanation"));
        record.put("rechargeNumber",id.toString());
        record.put("fundDestination",3);
        Integer integer1 = this.baseMapper.insertRetentionMoney(record);
        if (integer > 0 && integer1 > 0){
            return ResponseResult.success();
        }

        return ResponseResult.fail();
    }

    @Override
    public ResponseResult queryAudit(Map<String, Object> map) {
        boolean isExistToken = RedisUtil.exists(YFConfig.YF_PLATFORM_TOKEN_USER + String.valueOf(map.get("token")));

        if (!isExistToken) {
            return ResponseResult.fail(BizCodeEnume.INSUFFICIENT_PERMISSIONS);
        }
        HashMap<Object, Object> hashMap = new HashMap<>();
        if (StringUtil.isEmpty(String.valueOf(map.get("startTime")))){
            map.put("startTime",null);
        }
        if (StringUtil.isEmpty(String.valueOf(map.get("endTime")))){
            map.put("endTime",null);
        }
        IPage<PayRecordVO> page=this.baseMapper.queryRecord2(new Query<PayRecordVO>().getPage(map),
                map);
        if (page.getRecords() != null && page.getRecords().size() > 0) {
            for (PayRecordVO payRecordEntity : page.getRecords()) {
                String payImg = payRecordEntity.getPayImg();
                List<String> strings = JSON.parseArray(payImg, String.class);
                payRecordEntity.setPayImgs(strings);
            }
        }

        return ResponseResult.success(PageUtils.getPage(page));
    }

    @Override
    public ResponseResult processPayment(Map<String, Object> map) {
        boolean isExistToken = RedisUtil.exists(YFConfig.YF_PLATFORM_TOKEN_USER + String.valueOf(map.get("token")));

        if (!isExistToken) {
            return ResponseResult.fail(BizCodeEnume.INSUFFICIENT_PERMISSIONS);
        }
        Integer rechargeStatus = (Integer) map.get("rechargeStatus");
        String shopId = null;
        String userId = null;
        String userName = null;
        String content = "亲爱的卖家您好，您的质保金付款凭证审核失败，请登录商家后台查看原因。";

        PayRecordVO rechargeId = this.baseMapper.queryRecordId((Integer) map.get("rechargeId"));
        shopId = rechargeId.getShopId().toString();
        userId = rechargeId.getUserId();
        if (rechargeStatus == 1){
            //审核成功
            BigDecimal rechargeAmount = rechargeId.getRechargeAmount();//获取充值金额

            //将投诉成功未赔付的投诉单进行赔付
            unpaidorders(rechargeAmount,shopId);

            //更新质保金余额
            addshopmoney(shopId, rechargeAmount);
            content = "亲爱的卖家您好，您的质保金付款凭证审核成功，质保金充值成功。";
        }
        Integer integer = this.baseMapper.updateRecord(map);

        //发送消息通知
        this.baseMapper.insertSysMessage("",userId,"",5,"对公转账审核通知",content, String.valueOf(shopId));

        if (integer > 0){
            return ResponseResult.success();
        }
        return ResponseResult.fail();
    }

    //充值质保金
    @Transactional
    public Integer addshopmoney(String shopId,BigDecimal amount){

        //查询质保金信息
        RetentionShopInfoVO selectretention = this.baseMapper.selectRetention(shopId);

        BigDecimal payPrice = selectretention.getRetentionMoneyBalance().add(amount);//质保金余额 + 充值金额

        //质保金可提现
        BigDecimal payPrice1 = payPrice.subtract(selectretention.getRetentionMoneyLimit());
        if (payPrice1.compareTo(new BigDecimal(0)) == -1){
            payPrice1 = new BigDecimal(0);
        }

        //待补缴
        BigDecimal payPrice2 = selectretention.getRetentionMoneyPayment().subtract(amount);//待补缴金额
        if (payPrice2.compareTo(new BigDecimal(0)) == -1){
            payPrice2 = new BigDecimal(0);
        }

        HashMap<String, Object> map = new HashMap<>();
        map.put("shopId",shopId);
        map.put("payPrice",payPrice);
        map.put("payPrice1",payPrice1);
        map.put("payPrice2",payPrice2);
        if (payPrice.compareTo(selectretention.getRetentionMoneyLimit()) >= 0) {
            map.put("retentionStatus", 1);
        } else if (payPrice.compareTo(new BigDecimal(0)) >= 0 && payPrice2.compareTo(new BigDecimal(0)) > 0) {
            //发送站内信
            String content = "亲爱的卖家您好，根据平台质保金规则您需补缴" + payPrice2 + " 元质保金，请登录商家后台查询。";
            this.baseMapper.insertSysMessage("",selectretention.getUserId(),"",5,
                    "补缴质保金",content, String.valueOf(selectretention.getShopId()));

            map.put("retentionStatus", 2);
        } else if (payPrice.compareTo(new BigDecimal(0)) == -1) {
            map.put("retentionStatus", 3);
        }
        //更新shopbase表
        if(selectretention.getRetentionStatus() == 3){
            map.put("paymentTime", null);
        }
        return this.baseMapper.updateshopbase(map);
    }

    @Transactional
    public Integer determinedeliverytime2(String userId,BigDecimal money,String orderId){
        Map<String,Object> assetDetailMap = new HashMap<>();
        Map<String,Object> ManageMoney = new HashMap<>();

        //退回用户余额
        assetDetailMap.put("detailType", 12);
        assetDetailMap.put("assetType", 1);
        assetDetailMap.put("assetAmount", money);
        assetDetailMap.put("assetDirection", "平台罚款商家质保金");
        assetDetailMap.put("payType", 1);
        assetDetailMap.put("userId", userId);
        assetDetailMap.put("orderId", orderId);
        ManageMoney.put("money", money);
        ManageMoney.put("userId", userId);
        Integer integer = this.baseMapper.updateCardMemberDetailPort2(ManageMoney);


        this.baseMapper.insertDetail(assetDetailMap);

        Map<String, Object> comRecord = new HashMap<String, Object>();
        SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd");
        String recordDate = dateformat.format(new Date());
        String[] reDate = recordDate.split("-");
        String year = reDate[0];
        String month = reDate[1];
        String day = reDate[2];
        String recordTitle = "平台罚款商家质保金";
        String record_desc = "平台罚款商家质保金";
        int tradeTypeId = 3;
        int userType = 1;
        int recordWithdraw = 0;
        double osCommisAmount = 0;
        double osCommisReturnAmount = 0;
        comRecord.put("recordDate", recordDate);
        comRecord.put("recordMoney", money);
        comRecord.put("orderId", money);
        comRecord.put("year", year);
        comRecord.put("month", month);
        comRecord.put("day", day);
        comRecord.put("plusOrMinus", 1);
        comRecord.put("recordTitle", recordTitle);
        comRecord.put("record_desc", record_desc);
        comRecord.put("tradeTypeId", tradeTypeId);
        comRecord.put("userType", userType);
        comRecord.put("recordWithdraw", recordWithdraw);
        comRecord.put("osCommisAmount", osCommisAmount);
        comRecord.put("osCommisReturnAmount", osCommisReturnAmount);
        comRecord.put("money", money);
        comRecord.put("userId", userId);
        comRecord.put("isCurrentUser", 1);//判断当前订单是否属于当前用户 1 是 2 否
        this.baseMapper.insertConsumeRecordport(comRecord);

        if (integer > 0){
            return 1;
        }
        return 2;
    }




    //罚扣质保金
    public Integer updateshopmoney(Integer shopId,BigDecimal amount){
        //标明是否赔付
        Integer compensation = 1;
        ShopBaseEntity selectretention = shopBaseMapper.selectById(shopId);
        System.out.println("--------------------------------");
        System.out.println(selectretention);
        BigDecimal payPrice = selectretention.getRetentionMoneyBalance().subtract(amount);//质保金余额
        if (payPrice.compareTo(BigDecimal.valueOf(0)) == -1){
            compensation = 0;//未赔付
        }

        //质保金可提现
        BigDecimal payPrice1 = payPrice.subtract(selectretention.getRetentionMoneyLimit());
        if (payPrice1.compareTo(BigDecimal.valueOf(0)) == -1) {
            payPrice1 = new BigDecimal(0);
        }
        System.out.println("------------------------");
        System.out.println(shopId);
        System.out.println(amount);
        //待补缴
        BigDecimal payPrice2 = BigDecimal.valueOf(0);
        if (payPrice.compareTo(selectretention.getRetentionMoneyLimit()) < 0) {
            payPrice2 = selectretention.getRetentionMoneyLimit().subtract(payPrice);//待补缴金额
            if (payPrice2.compareTo(BigDecimal.valueOf(0)) == -1) {
                payPrice2 = BigDecimal.valueOf(0);
            }
        }

        //累计赔付金额
        BigDecimal payPrice3 = selectretention.getAccumulatedCompensation()==null?new BigDecimal(0):selectretention.getAccumulatedCompensation().add(amount);
        HashMap<String, Object> paymap = new HashMap<>();
        paymap.put("payPrice", payPrice);
        paymap.put("payPrice1", payPrice1);
        paymap.put("payPrice2", payPrice2);
        paymap.put("payPrice3", payPrice3);
        paymap.put("shopId", shopId);
        if (payPrice.compareTo(selectretention.getRetentionMoneyLimit()) >= 0) {
            paymap.put("retentionStatus", 1);
        } else if (payPrice.compareTo(BigDecimal.valueOf(0)) >= 0 && payPrice2.compareTo(BigDecimal.valueOf(0)) > 0) {
            //发送站内信
            String content = "亲爱的卖家您好，根据平台质保金规则您需补缴" + payPrice2 + " 元质保金，请登录商家后台查询。";
            this.baseMapper.insertSysMessage("",selectretention.getUserId(),"",5,
                    "补缴质保金",content, String.valueOf(shopId));

            paymap.put("retentionStatus", 2);
        } else if (payPrice.compareTo(BigDecimal.valueOf(0)) == -1) {
            //发送站内信
            String content = "亲爱的卖家您好，根据平台质保金规则您需补缴" + payPrice2 + " 元质保金，请登录商家后台查询。";
            this.baseMapper.insertSysMessage("",selectretention.getUserId(),"",5,
                    "补缴质保金",content, String.valueOf(shopId));

            paymap.put("retentionStatus", 3);
            paymap.put("paymentTime", new Date());
        }
        //更新shopbase表
        if(selectretention.getRetentionStatus() == 3){
            paymap.put("paymentTime", null);
        }
        this.baseMapper.updateshopbase(paymap);
        return compensation;
    }



    //提现质保金
    public Integer updateshopmoney1(Integer shopId,BigDecimal amount){
        //标明是否赔付
        Integer compensation = 1;
        ShopBaseEntity selectretention = shopBaseMapper.selectById(shopId);
        BigDecimal payPrice = selectretention.getRetentionMoneyBalance().subtract(amount);//质保金余额
        if (payPrice.compareTo(BigDecimal.valueOf(0)) == -1){
            compensation = 0;//未赔付
        }

        //质保金可提现
        BigDecimal payPrice1 = payPrice.subtract(selectretention.getRetentionMoneyLimit());
        if (payPrice1.compareTo(BigDecimal.valueOf(0)) == -1) {
            payPrice1 = new BigDecimal(0);
        }

        //待补缴
        BigDecimal payPrice2 = BigDecimal.valueOf(0);
        if (payPrice.compareTo(selectretention.getRetentionMoneyLimit()) < 0) {
            payPrice2 = selectretention.getRetentionMoneyLimit().subtract(payPrice);//待补缴金额
            if (payPrice2.compareTo(BigDecimal.valueOf(0)) == -1) {
                payPrice2 = BigDecimal.valueOf(0);
            }
        }


        HashMap<Object, Object> paymap = new HashMap<>();
        paymap.put("payPrice", payPrice);
        paymap.put("payPrice1", payPrice1);
        paymap.put("payPrice2", payPrice2);
        paymap.put("shopId", shopId);
        if (payPrice.compareTo(selectretention.getRetentionMoneyLimit()) >= 0) {
            paymap.put("retentionStatus", 1);
        } else if (payPrice.compareTo(BigDecimal.valueOf(0)) >= 0 && payPrice2.compareTo(BigDecimal.valueOf(0)) > 0) {
            //发送站内信
            String content = "亲爱的卖家您好，根据平台质保金规则您需补缴" + payPrice2 + " 元质保金，请登录商家后台查询。";
            this.shopBaseMapper.insertSysMessage("",selectretention.getUserId(),"",5,
                    "补缴质保金",content, String.valueOf(shopId));

            paymap.put("retentionStatus", 2);
        } else if (payPrice.compareTo(BigDecimal.valueOf(0)) == -1) {
            //发送站内信
            String content = "亲爱的卖家您好，根据平台质保金规则您需补缴" + payPrice2 + " 元质保金，请登录商家后台查询。";
            this.shopBaseMapper.insertSysMessage("",selectretention.getUserId(),"",5,
                    "补缴质保金",content, String.valueOf(shopId));

            paymap.put("retentionStatus", 3);
            paymap.put("paymentTime", new Date());
        }
        //更新shopbase表
        if(selectretention.getRetentionStatus() == 3){
            paymap.put("paymentTime", null);
        }
        this.shopBaseMapper.updateshopbase(paymap);
        return compensation;
    }


    //查询是否有未赔付投诉单
    public void unpaidorders(BigDecimal amount,String shopId){
        //查询未赔付投诉单
        List<OrderComplaintsVO> unpaidcomplaints = this.baseMapper.unpaidcomplaints(shopId);
        if (unpaidcomplaints != null && unpaidcomplaints.size() > 0){
            for (OrderComplaintsVO unpaidcomplaint : unpaidcomplaints) {
                BigDecimal decimal = unpaidcomplaint.getCompensationAmount();//赔付金额

                if (amount.compareTo(decimal) < 0){
                    continue;
                }

                if (amount.compareTo(decimal) >= 0){

                    if (unpaidcomplaint.getFundDestination() == 1) {
                        //将赔付金额发放进用户余额
                        insert(unpaidcomplaint.getUserId(), unpaidcomplaint.getCompensationAmount().toString(), unpaidcomplaint.getOrderId());
                    }
                    //修改投诉单赔付状态
                    this.baseMapper.updateispay(unpaidcomplaint.getId());
                    //充值的金额足够赔付
                    amount = amount.subtract(decimal);
                }

                if (amount .compareTo(new BigDecimal(0)) <= 0){
                    return;
                }
            }
        }
    }
    //将金额存入用户余额
    @Transactional
    public Integer insert(String userId,String amount,String orderId){
        Map assetDetailMap = new HashMap<>();
        Map ManageMoney = new HashMap<>();
        Map map = new HashMap<>();
        //查询账户余额
        String balance = this.baseMapper.queryAccountBalance(userId);

        Double Money = Double.parseDouble(balance) + Double.parseDouble(amount);
        //余额充值
        assetDetailMap.put("detailType", 12);//12 投诉退款
        assetDetailMap.put("assetType", 1);
        assetDetailMap.put("assetAmount", Double.parseDouble(amount));
        assetDetailMap.put("assetDirection", "投诉退款");
        assetDetailMap.put("payType", 1);//
        assetDetailMap.put("orderId", orderId);
        assetDetailMap.put("userId", userId);
        ManageMoney.put("money", Money);
        ManageMoney.put("userId", userId);
        this.baseMapper.updateCardMemberDetailPort(ManageMoney);

        this.baseMapper.insertDetail(assetDetailMap);

        Map<String, Object> comRecord = new HashMap<String, Object>();
        SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd");
        String recordDate = dateformat.format(new Date());
        String[] reDate = recordDate.split("-");
        String year = reDate[0];
        String month = reDate[1];
        String day = reDate[2];
        String recordTitle = "投诉退款";
        String record_desc = "投诉退款";
        int tradeTypeId = 3;
        int userType = 1;
        int recordWithdraw = 0;
        double osCommisAmount = 0;
        double osCommisReturnAmount = 0;
        comRecord.put("recordDate", recordDate);
        comRecord.put("recordMoney", amount);
        comRecord.put("year", year);
        comRecord.put("orderId", orderId);
        comRecord.put("month", month);
        comRecord.put("day", day);
        comRecord.put("plusOrMinus", 1);
        comRecord.put("recordTitle", recordTitle);
        comRecord.put("record_desc", record_desc);
        comRecord.put("tradeTypeId", tradeTypeId);
        comRecord.put("userType", userType);
        comRecord.put("recordWithdraw", recordWithdraw);
        comRecord.put("osCommisAmount", osCommisAmount);
        comRecord.put("osCommisReturnAmount", osCommisReturnAmount);
        comRecord.put("money", Money);
        comRecord.put("userId", userId);
        comRecord.put("isCurrentUser",1);//判断当前订单是否属于当前用户 1 是 2 否
        this.baseMapper.insertConsumeRecordport(comRecord);

        return 1;
    }
}
